
cd('.')
addpath('matlab functions')

D0 = readtable('NC Data/SCC_4to5.csv');
D0.intercept(:) = 1;

vamdl = struct();
vamdl.math = load('output/main/vam_math_matching.mat');
vamdl.reading = load('output/main/vam_reading_matching.mat');

% first stage;
fs = vamdl.math.controls;
fs.order = (1:size(fs,1))';
fs = innerjoin(fs,vamdl.reading.controls,'Keys','Row');
fs = sortrows(fs,'order');
fs('intercept',:) = [];
fs = removevars(fs,'order');
tbl = [strrep(fs.Properties.RowNames,'_',' ') table2cell(fs)];
nstar = cellfun(@(c,s) countstars(c,s),tbl(:,[2 4]),tbl(:,[3 5]),'unif',0);
tbl(:,[2 4]) = cellfun(@(x,s) sprintf('$%0.4f^{%s}$',x,s),tbl(:,[2 4]),nstar,'unif',0);
tbl(:,[3 5]) = cellfun(@(x) sprintf('(%0.4f)',x),tbl(:,[3 5]),'unif',0);

latextbl(tbl,... 
    'tables and figures/tables/coefficients.tex', ...
    {'%s','%s','%s','%s','%s'});

mkse = @(c,s) sprintf('\\makecell{%0.4f \\\\ {\\footnotesize (%0.4f)}}',c,s); 

% Distribution

TBL = struct();
for sbj = {'math','reading'}

    c_m_est = bsxfun(@minus,vamdl.(sbj{1}).VAdistEstimates.mean,vamdl.(sbj{1}).VAmomentEstimates.mean);
    c_m_se = vamdl.(sbj{1}).VAdistStandardErrors.mean;
    c_m = arrayfun(mkse,c_m_est,c_m_se,'unif',0);

    c_v_est = [diag(vamdl.(sbj{1}).VAdistEstimates.cov(:,:,1)) diag(vamdl.(sbj{1}).VAdistEstimates.cov(:,:,2))];
    c_v_var = [diag(vamdl.(sbj{1}).VAdistStandardErrors.cov(:,:,1)) diag(vamdl.(sbj{1}).VAdistStandardErrors.cov(:,:,2))].^2;
    c_sd_se = arrayfun(@(x,c) sqrt(deltamethod(@(v) sqrt(v),x,c)),c_v_est,c_v_var,'unif',0);
    c_sd_est = num2cell(sqrt(c_v_est));
    c_sd = cellfun(mkse,c_sd_est,c_sd_se,'unif',0);

    p_sd_se = vamdl.(sbj{1}).VAmomentStandardErrors.sd';
    p_sd_est = vamdl.(sbj{1}).VAmomentEstimates.sd';
    p_sd = arrayfun(mkse,p_sd_est,p_sd_se,'unif',0);

    tbl = [vamdl.(sbj{1}).tchcoef' c_m(:,1) c_sd(:,1) c_m(:,2) c_sd(:,2) p_sd];
    tbl(:,1) = regexprep(tbl(:,1),'lag_(math|reading)score_sq','\$A_\{t-1\}^2\$');
    tbl(:,1) = regexprep(tbl(:,1),'lag_(math|reading)score','\$A_\{t-1\}\$');
    tbl(:,1) = regexprep(tbl(:,1),'poverty','FRL');
    tbl(:,1) = regexprep(tbl(:,1),'female','FEM');
    tbl(:,1) = regexprep(tbl(:,1),'race_black','BL');
    tbl(:,1) = regexprep(tbl(:,1),'lep','LEP');
    tbl(:,1) = regexprep(tbl(:,1),'^([^X]+)X(.+)','($1 \$\\times\$ $2)');
    tbl(:,1) = regexprep(tbl(:,1),'^yr','Year 20');
    tbl(:,1) = strcat(tbl(:,1),' ($\delta_{',num2str((1:size(tbl,1))'),'}$)');

    TBL.(sbj{1}) = tbl;
end

latextbl(TBL.math,... 
    'tables and figures/tables/math_dist.tex', ...
    {'%s','%s','%s','%s','%s','%s'});

latextbl(TBL.reading,... 
    'tables and figures/tables/reading_dist.tex', ...
    {'%s','%s','%s','%s','%s','%s'});


